package com.bookbuf.social.share.content.media.image.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * Created by robert on 16/7/4.
 */
public class ImageFormat {
	public static final int FORMAT_JPEG = 0;
	public static final int FORMAT_GIF = 1;
	public static final int FORMAT_PNG = 2;
	public static final int FORMAT_BMP = 3;
	public static final int FORMAT_PCX = 4;
	public static final int FORMAT_IFF = 5;
	public static final int FORMAT_RAS = 6;
	public static final int FORMAT_PBM = 7;
	public static final int FORMAT_PGM = 8;
	public static final int FORMAT_PPM = 9;
	public static final int FORMAT_PSD = 10;
	public static final int FORMAT_SWF = 11;
	public static final String[] FORMAT_NAMES = new String[]{"jpeg", "gif", "png", "bmp", "pcx", "iff", "ras", "pbm", "pgm", "ppm", "psd", "swf"};

	public ImageFormat () {
	}

	public static String checkFormat (byte[] fileBytes) {
		ByteArrayInputStream inputStream = null;

		try {
			inputStream = new ByteArrayInputStream (fileBytes);
			int head = inputStream.read ();
			int next = inputStream.read ();
			if (head == 0x47 && next == 0x49) {
				return FORMAT_NAMES[1];
			}

			if (head == 0x89 && next == 0x50) {
				return FORMAT_NAMES[2];
			}

			if (head == 0xFF && next == 0xD8) {
				return FORMAT_NAMES[0];
			}

			if (head == 0x42 && next == 0x4D) {
				return FORMAT_NAMES[3];
			}

			if (head == 0xA && next < 0x6) {
				return FORMAT_NAMES[4];
			}

			if (head == 0x46 && next == 0x4F) {
				return FORMAT_NAMES[5];
			}

			if (head == 0x59 && next == 0xA6) {
				return FORMAT_NAMES[6];
			}

			if (head == 0x50 && next >= 0x31 && next <= 0x36) {
				int var31 = next - 48;
				if (var31 >= 1 && var31 <= 6) {
					int[] ints = new int[]{7, 8, 9};
					int i = ints[(var31 - 1) % 3];
					return FORMAT_NAMES[i];
				}
				return "";
			}

			if (head == 0x38 && next == 0x42) {
				return FORMAT_NAMES[10];
			}

			if (head == 0x46 && next == 0x57) {
				return FORMAT_NAMES[11];
			}

			return "";
		} catch (Exception e) {
			e.printStackTrace ();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close ();
				} catch (IOException e) {
					e.printStackTrace ();
				}
			}

		}

		return "";
	}
}

